<script setup>
import { selectAllTask, selectTaskById, saveOrUpdate, selectUserInfo, selectSectionName } from '@/api/common/work/work.js'
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from 'element-plus'
import axios from 'axios';
import route from "@/router";
import { useRoute } from "vue-router";
import { useTokenStore } from "@/store/token.js";

const ret = useTokenStore()
const router = useRoute();
//作业模型
const sectionId = ref();
// 新增作业
const save = async () => {
  if (validateTask()) {
    console.log(task.value);
    const res = await saveOrUpdate(task.value);
    if (res != null) {
      ElMessage.success('编辑成功');
      setTimeout(() => {
        location.reload()
      }, 1000)

    }
  }
};
const courseId = ref();

onMounted(() => {
  let sectId = router.query.sectionId
  sectionId.value = sectId
  courseId.value = router.query.courseId
  getAllTask()
})

const task = ref({
  sectionId: router.query.sectionId,
  taskId: 0,
  teacherId: 0,
  taskName: "",
  taskInfo: ""
});

// 校验函数
const validateTask = () => {
  if (!task.value.taskName.trim()) {
    ElMessage.error('题目名称不能为空');
    return false;
  }
  return true;
};

const tasks = ref([])

const zuoye = ref(false)
//获取全部作业
const getAllTask = async () => {
  tasks.value = await (await selectAllTask(sectionId.value)).data
  if (tasks.value != null && tasks.value != '') {
    console.log(tasks.value)
    zuoye.value = true
  } else {
    zuoye.value = false
  }
}



//根据作业Id查询作业详情
const getTaskById = (taskId) => {

  selectTaskById(taskId).then(res => {
    task.value = res.data

  })

}
const suoyin = ref(0)
const xsid = ref(0)

//获取索引
const qu = (index) => {
  suoyin.value = index
}

const shang = () => {
  let Id = suoyin.value
  if (Id < 1) {
    ElMessage.error('没有上一题')
  } else {
    Id = Id - 1
    if (Id == 0) {
      ElMessage.error('没有上一题')
    }
    suoyin.value = Id
    for (let i = 0; i < tasks.value.length; i++) {
      if (i + 1 == Id) {
        getTaskById(tasks.value[i].taskId)
        return;
      }
    }
  }
}


const xia = () => {
  let Id = suoyin.value
  for (let i = 0; i < tasks.value.length; i++) {
    if (Id >= tasks.value.length) {
      ElMessage.error('没有下一题')
      return;
    }
  } 
  Id = Id + 1
  suoyin.value = Id
  for (let i = 0; i < tasks.value.length; i++) {
    if (Id == i + 1) {
      getTaskById(tasks.value[i].taskId)
      return;
    }
  }

}

//导入作业
function showFileChooser() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  input.click();

  input.addEventListener("change", async function () {
    const file = this.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    // 确保 sectionId 已被定义且能获取到值  
    const sectionIdElement = sectionId.value
    if (!sectionIdElement) {
      console.error('Element with id "sectionId" not found');
      return;
    }
    formData.append("sectionId", sectionId.value);

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/task/importData", true);
    xhr.setRequestHeader("Authorization", ret.token);
    xhr.onload = () => {
      if (xhr.status === 200) {
        // 请求成功，可以根据需要处理响应  
        console.log('File uploaded successfully');
        // 如果需要，可以在这里重载页面  
        ElMessage.success('导入成功')
        setTimeout(() => {
          location.reload()
        }, 1000)
      } else {
        // 处理错误  
        console.error('Error uploading file:', xhr.responseText);
      }
    };

    xhr.onerror = function () {
      // 网络错误处理  
      console.error('Network error');
    };

    xhr.send(formData);
  });
}

const getName = ref('')
//获取创建人名称
const getUserName = async () => {
  let res = await selectUserInfo()
  getName.value = res.data.nickName
}
getUserName()


//获取小节名称

const getSectionName = ref(null)


const sectionName = async () => {
  let res = await selectSectionName(router.query.sectionId)
  getSectionName.value = res.data.sectionName


}
sectionName()
</script>

<template>
  <!-- 头部 -->
  <header>
    <div class="header-img1">
      <img src="@/assets/img/左箭头.png" @click="route.push('/course/Course?courseId=' + courseId)" />
    </div>
    <div class="header-text">
      <span>新增作业</span>
    </div>
    <a href="https://prcpic.oss-cn-beijing.aliyuncs.com/%E4%BD%9C%E4%B8%9A%E6%A8%A1%E6%9D%BF1.xlsx">
      <div class="header-botton" style="border: 1px solid magenta;">
        <button>下载模板</button>
      </div>
    </a>

    <div class="header-botton" style="margin-right: 10px;">
      <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
      <button @click="showFileChooser()">导入作业</button>
    </div>
    
  </header>
  <!-- 主体 -->
  <main>
    <div class="main-box">
      <div class="main-left">
        <div class="main-left-title">
          <div><span>小节名称：</span></div>
          <el-input v-model="getSectionName" style="width: 240px" disabled placeholder="小节名称" />
          <div><span>创建人</span></div>
          <el-input v-model="getName" style="width: 240px" disabled placeholder="创建人" />
        </div>
      </div>
      <div class="main-main">
        <div class="main-main-content" :model="task">
          <div class="main-main-content-title">
            <div class="div1">
              <span>题目名称：</span><br>
              <!-- <input type="text" placeholder="请输入" v-model="task.taskName" /> -->
              <el-input v-model="task.taskName" style="width: 630px" :rows="8" type="textarea" placeholder="请输入题目" />
            </div>
            <div class="div2">
              <span>题目答案：</span>
            </div>
            <div class="div3">
              <el-input v-model="task.taskInfo" style="width: 630px" :rows="9" type="textarea" placeholder="请输入答案" />
              <!-- <textarea v-model="task.taskInfo" placeholder="请输入"></textarea> -->
            </div>
          </div>
          <div class="div6"></div>
          <button class="tianjia" @click="save">编辑作业</button>
        </div>
        <div class="main-bottom">

          <button @click="shang()">上一题</button>
          <button @click="xia()">下一题</button>
        </div>
      </div>
      <!--  有数据时 -->
      <div class="main-right" v-if="zuoye">
        <div class="main-right-title">
          <div class="box-110">
            <div class="text" :class="{ selectnow: index + 1 == suoyin }" v-for="(item, index) in tasks"
              :key="item.taskId" @click="getTaskById(item.taskId), qu(index + 1)">
              <span>{{ index + 1 }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 没有数据时 -->
      <div class="main-right" v-else>
        <div class="main-right-title">
          <div class="box-110">
            <span>暂无作业</span>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

header {
  width: 100%;
  height: 80px;
  box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.2);
  background-color: #fff;

  .header-img1 {
    width: 50px;
    height: 57px;
    float: left;
    margin-top: 11px;
    margin-left: 62px;
    border-radius: 1rem;

    img {
      width: 27px;
      margin-left: 9px;
      margin-top: 15px;
    }
  }

  .header-text {
    width: 121px;
    height: 39px;
    float: left;
    margin-top: 21px;
    font-size: 26px;
    color: #000;
    font-weight: bold;
    font-family: "微软雅黑";
    text-align: center;
  }

  .header-botton {
    width: 100px;
    height: 39px;
    background-color: #ccc;
    margin-top: 20px;
    margin-right: 60px;
    float: right;
    border-radius: 0.6rem;

    button {
      width: 100px;
      height: 39px;
      border: none;
      background-color: rgb(242, 57, 40);
      border-radius: 0.6rem;
      font-size: 16px;
      color: #fff;
      cursor: pointer;
    }
  }
}

main {
  width: 95%;
  position: absolute;

  .main-box {
    width: 1540px;
    margin: 0 auto;

    .main-left {
      width: 380px;
      float: left;

      .main-left-title {
        width: 280px;
        height: 324px;
        margin-top: 101px;
        margin-left: 48px;
        box-shadow: 0 0 5px rgba(225, 225, 225);
        border: 1px solid rgb(255, 255, 255);

        div {
          width: 200px;
          height: 30px;
          margin-left: 25px;
          margin-top: 20px;

          span {
            line-height: 20px;
            font-size: 16px;
            font-weight: bold;
          }
        }

        input {
          width: 231px;
          height: 30px;
          margin-left: 22px;
          outline: none;
          text-indent: 10px;
          font-size: 12px;
        }

        button {
          width: 100px;
          height: 30px;
          margin-top: 25px;
          margin-left: 23px;
          /* background-color: #f6f6f6; */
          border: none;
          font-size: 13px;
          cursor: pointer;
        }

        button:hover {
          background-color: rgb(242, 57, 40);
          color: black;
        }
      }
    }

    .main-main {
      width: 780px;
      float: left;
      border-left: 1px solid #ccc;
      border-right: 1px solid #ccc;

      .main-main-button {
        width: 130px;
        height: 30px;
        margin-top: 30px;
        float: right;

        button {
          width: 80px;
          height: 30px;
          background-color: #f7f7f7;
          color: black;
          border: none;
          border-radius: 0.3rem;
          font-size: 12px;
          cursor: pointer;
        }

        button:hover {
          background-color: rgb(242, 57, 40);
          color: #fff;
        }
      }

      .main-main-content {
        width: 669px;
        height: 515px;
        border: 1px solid #ccc;
        margin: 0 auto;
        margin-top: 80px;

        .main-main-content-title {
          width: 621px;
          height: 213px;
          margin: 0 auto;

          span {
            font-size: 18px;
          }

          .div1 {
            width: 669px;
            height: 30px;
            margin-top: 15px;

            input {
              width: 500px;
              height: 30px;
              outline: none;
              font-size: 14px;
              text-indent: 10px;
            }
          }

          .div2 {
            width: 620px;
            height: 30px;
            margin-top: 37px;
            margin-top: 180px;

            span {
              font-size: 16px;
            }
          }

          .div3 {
            width: 615px;
            height: 291px;

            textarea {
              width: 615px;
              height: 200px;
              outline: none;
              font-size: 18px;
              text-indent: 26px;
              line-height: 33px;
              // margin-top: 150px;
              resize: none;
              overflow-y: scroll;

              &::-webkit-scrollbar {
                display: none;
              }
            }
          }
        }

        .div6 {
          width: 669px;
          height: 30px;
        }
      }

      .main-bottom {
        width: 298px;
        height: 36px;
        float: right;
        margin-top: 44px;

        button {
          width: 100px;
          height: 36px;
          background-color: rgb(242, 57, 40);
          border: none;
          color: #fff;
          margin-left: 20px;
          font-size: 14px;
          border-radius: 0.5rem;
          cursor: pointer;
          transition: all 0.5s;

          &:hover {
            transform: scale(1.2);
          }
        }
      }
    }

    .tianjia {
      margin-left: 530PX;
      margin-top: 210PX;
      width: 100PX;
      height: 40PX;
      background-color: rgb(242, 57, 40);
      border: 0;
      border-radius: 0.5rem;
      color: #fff;

      &:hover {
        background-color: rgb(242, 57, 40);
        color: #fff;
        transform: scale(1.2);
      }
    }

    .main-right {
      width: 380px;
      float: left;

      .main-right-title {
        width: 372px;
        // height: 524px;
        margin-top: 101px;
        margin-left: 48px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;

        .box-110 {
          width: 330px;
          margin: 10px 0 10px 0;
          max-height: 400px;
          display: flex;
          flex-wrap: wrap;
          flex-direction: row;
          overflow-y: scroll;

          &::-webkit-scrollbar {
            display: none;
          }

          .text {
            width: 50px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            font-size: 25px;
            margin: 8px 0 8px 4px;
            cursor: pointer;
            box-shadow: 0 0 5px rgba(225, 225, 225);
            border: 1px solid rgb(255, 255, 255);
            border-radius: 0.5rem;
            transition: all 0.5s;

            &:hover {
              background-color: rgb(242, 57, 40);
              color: #fff;
              transform: scale(1.2);
            }
          }

          // .text: {
          //   background-color: rgb(242, 57, 40);
          //   color: #fff;
          // }

          .selectnow {
            background-color: rgb(242, 57, 40);
            color: #fff;
          }
        }
      }
    }
  }
}
</style>